package com.zhongli.devplatform.service.impl.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongli.devplatform.mapper.sys.ReadResourceMapper;
import com.zhongli.devplatform.mapper.sys.ReadRoleResourceMapper;
import com.zhongli.devplatform.po.sys.ReadResourcePO;
import com.zhongli.devplatform.service.imp.sys.ReadSecurityMetadataSourceService;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class SecurityMetadataSourceServiceImpl implements ReadSecurityMetadataSourceService {

    private Map<String, List<ConfigAttribute>> map = new HashedMap<>();

    @Autowired
    private ReadResourceMapper resourceMapper;

    @Autowired
    private ReadRoleResourceMapper readRoleResourceMapper;


    /**
     * 初始化资源信息
     */
    @Override
    @PostConstruct
    public void initMetadataSource() {
        map.clear();
        List<ReadResourcePO> readResourcePOList = resourceMapper.selectList(new QueryWrapper<ReadResourcePO>().ne("filter_type", "anon"));
        for (ReadResourcePO readResourcePO : readResourcePOList) {
            List<ConfigAttribute> configAttributes = new ArrayList<>();
            List<String> roleCodes = readRoleResourceMapper.listRoleCodeByResource(readResourcePO.getId());
            if (roleCodes.isEmpty()) {
                configAttributes.add(new SecurityConfig(readResourcePO.getFilterType()));
            } else {
                for (String roleCode : roleCodes) {
                    configAttributes.add(new SecurityConfig(roleCode));
                }
            }
            map.put(readResourcePO.getUrl(), configAttributes);
        }
    }

    @Override
    public List<ConfigAttribute> getConfigAttributesByUrl(String url) {
        return map.get(url);
    }
}
